module Debouncer (
    input sys_clk,
    input key_in,
    input sys_rst,
    output reg  key_out
);

parameter clkdiver = 50000000/100; //20ms

reg [19:0] cnt_20ms;

always @(posedge sys_clk or posedge sys_rst) 
begin
    if (sys_rst == 1'b1) begin
        cnt_20ms <= 20'b0;
    end
    else if (key_in == 1'b1) begin
        cnt_20ms <= 20'b0;
    end
    else if (key_in == 1'b0 && cnt_20ms == clkdiver) begin
        cnt_20ms <= cnt_20ms;
    end
    else begin
        cnt_20ms <= cnt_20ms + 1'b1;
    end
end

always @(posedge sys_clk or posedge sys_rst ) begin
    if (sys_rst == 1'b1) begin
        key_out <= 1'b0;
    end
    else if (cnt_20ms == clkdiver - 1'b1) begin
        key_out <= 1'b1;
    end
    else begin
        key_out <= 1'b0;
    end
end

endmodule